package cmsapi

import (
	// "net/http"
	"encoding/json"
	"strconv"
	"time"

	// "github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
	"gopkg.in/mgo.v2/bson"
	"oxy_server/model"
	"oxy_server/module/log"
	"oxy_server/res/cmsserver/skuorder"
	"oxy_server/until"
)

type (
	product struct {
		ID               bson.ObjectId `json:"_id" bson:"_id"`
		LargeCargoNumber string        `json:"largecargonumber" bson:"largecargonumber"`
		FactoryNumber    string        `json:"factorynumber" bson:"factorynumber"`
		SupplierName     string        `json:"suppliername" bson:"suppliername"`
		StyleName        string        `json:"stylename" bson:"stylename"`
		Picture          string        `json:"picture" bson:"picture"`
		Gender           string        `json:"gender" bson:"gender"`
		ProductCategory  string        `json:"productcategory" bson:"productcategory"`
		ProductKind      string        `json:"productkind" bson:"productkind"`
		Season           string        `json:"season" bson:"season"`
		Year             string        `json:"year" bson:"year"`
		Color            string        `json:"color" bson:"color"`
		Cost             string        `json:"cost" bson:"cost"`
		Price            string        `json:"price" bson:"price"`
		NewMonthPlan     string        `json:"newmonthplan" bson:"newmonthplan"`
		WhetherMeet      string        `json:"whethermeet" bson:"whethermeet"`
		WhetherNew       string        `json:"whethernew" bson:"whethernew"`
		Problem          string        `json:"problem" bson:"problem"`
		ProductionTeam   string        `json:"productionteam" bson:"productionteam"`
		DesignTeam       string        `json:"designteam" bson:"designteam"`
		EditionTeam      string        `json:"editionteam" bson:"editionteam"`
		OperationTeam    string        `json:"operationteam" bson:"operationteam"`
		PhotographyTeam  string        `json:"photographyteam" bson:"photographyteam"`
		PlaneTeam        string        `json:"planeteam" bson:"planeteam"`
		WashPic          string        `json:"washpic" bson:"washpic"`
		NewWashPic       []string      `json:"newwashpic" bson:"newwashpic"`

		Factorymodelnumber  string    `json:"factorymodelnumber" bson:"factorymodelnumber"`
		Person              string    `json:"person" bson:"person"`
		IsEdiet             bool      `json:"isedit" bson:"isedit"`
		CertificateSupplier string    `json:"certificatesupplier" bson:"certificatesupplier"`
		ClothingSupplier    string    `json:"clothingsupplier" bson:"clothingsupplier"`
		SizemarkSupplier    string    `json:"sizemarksupplier" bson:"sizemarksupplier"`
		WatermarkSupplier   string    `json:"watermarksupplier" bson:"watermarksupplier"`
		NewDay              time.Time `json:"newday" bson:"newday"`
		OrderCount          int       `json:"ordercount" bson:"ordercount"`
		Count               int       `json:"count" bson:"count"`
		InboundDate         time.Time `json:"inbounddate" bson:"inbounddate"`
	}
	insertproduct struct {
		LargeCargoNumber    string    `json:"largecargonumber" bson:"largecargonumber"`
		FactoryNumber       string    `json:"factorynumber" bson:"factorynumber"`
		SupplierName        string    `json:"suppliername" bson:"suppliername"`
		StyleName           string    `json:"stylename" bson:"stylename"`
		Picture             string    `json:"picture" bson:"picture"`
		Gender              string    `json:"gender" bson:"gender"`
		ProductCategory     string    `json:"productcategory" bson:"productcategory"`
		ProductKind         string    `json:"productkind" bson:"productkind"`
		Season              string    `json:"season" bson:"season"`
		Year                string    `json:"year" bson:"year"`
		Color               string    `json:"color" bson:"color"`
		Cost                string    `json:"cost" bson:"cost"`
		Price               string    `json:"price" bson:"price"`
		NewMonthPlan        string    `json:"newmonthplan" bson:"newmonthplan"`
		WhetherMeet         string    `json:"whethermeet" bson:"whethermeet"`
		WhetherNew          string    `json:"whethernew" bson:"whethernew"`
		Problem             string    `json:"problem" bson:"problem"`
		ProductionTeam      string    `json:"productionteam" bson:"productionteam"`
		DesignTeam          string    `json:"designteam" bson:"designteam"`
		EditionTeam         string    `json:"editionteam" bson:"editionteam"`
		OperationTeam       string    `json:"operationteam" bson:"operationteam"`
		PhotographyTeam     string    `json:"photographyteam" bson:"photographyteam"`
		PlaneTeam           string    `json:"planeteam" bson:"planeteam"`
		WashPic             string    `json:"washpic" bson:"washpic"`
		NewWashPic          []string  `json:"newwashpic" bson:"newwashpic"`
		Factorymodelnumber  string    `json:"factorymodelnumber" bson:"factorymodelnumber"`
		Person              string    `json:"person" bson:"person"`
		IsEdiet             bool      `json:"isedit" bson:"isedit"`
		OrderCount          int       `json:"ordercount" bson:"ordercount"`
		Count               int       `json:"count" bson:"count"`
		CertificateSupplier string    `json:"certificatesupplier" bson:"certificatesupplier"`
		ClothingSupplier    string    `json:"clothingsupplier" bson:"clothingsupplier"`
		SizemarkSupplier    string    `json:"sizemarksupplier" bson:"sizemarksupplier"`
		WatermarkSupplier   string    `json:"watermarksupplier" bson:"watermarksupplier"`
		NewDay              time.Time `json:"newday" bson:"newday"`
		InboundDate         time.Time `json:"inbounddate" bson:"inbounddate"`
	}
)

func GetProductListHandler(c echo.Context) error {
	currentpage, err := strconv.Atoi(c.QueryParam("currentpage"))
	perpage, err := strconv.Atoi(c.QueryParam("perpage"))
	jsonquery := c.QueryParam("like")
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "products"
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	query, count, err := model.DB().Query(M, currentpage, perpage)
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []product{}
	query.All(&ps)
	for key, _ := range ps {
		model.DB().Dbname = "OxyCms"
		model.DB().Document = "sku_order"
		skuorderList := []skuorder.Skuorder{}
		queryorder, _, err := model.DB().Query(bson.M{"skudesc": ps[key].LargeCargoNumber}, 0, 0)
		if err != nil {
			log.Error("计算产品下单数入库数出错", err)
			c.JSON(404, map[string]interface{}{
				"msg": "error",
			})
			return err
		}
		queryorder.All(&skuorderList)
		ps[key].OrderCount = 0
		ps[key].Count = 0
		for _, order := range skuorderList {
			OrderCount, _ := strconv.Atoi(order.OrderCount)
			Count, _ := strconv.Atoi(order.Count)
			ps[key].OrderCount += OrderCount
			ps[key].Count += Count
		}

		var obj = []productiongroup{}
		model.DB().Document = "production_group"
		queryList, _, err := model.DB().Query(bson.M{"productid": ps[key].ID.Hex()}, 0, 0)

		if err != nil {
			log.Error("production_group查询出错", err)
			c.JSON(403, map[string]interface{}{
				"msg": "error",
			})
			return err
		}
		queryList.All(&obj)
		for _, groupList := range obj {
			ps[key].CertificateSupplier = groupList.CertificateSupplier
			ps[key].ClothingSupplier = groupList.ClothingSupplier
			ps[key].SizemarkSupplier = groupList.SizemarkSupplier
			ps[key].WatermarkSupplier = groupList.WatermarkSupplier
			ps[key].InboundDate = groupList.InboundDate
		}
	}
	str, err := json.Marshal(ps)
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":   "success",
		"data":  string(str),
		"count": count,
	})

	return nil
}

func AddProductHandler(c echo.Context) error {
	p := &insertproduct{}
	if err := c.Bind(p); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "products"
	err := model.DB().Insert(p)
	if err != nil {
		log.Error("插入出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	M := bson.M{}
	data, err1 := bson.Marshal(p)
	if err1 != nil {
		log.Info("interface ->字符流", err1)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err1
	}
	err = bson.Unmarshal(data, &M)
	if err != nil {
		log.Info("字符流->bson.M", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	query, err := model.DB().QueryOne(M)
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	p1 := product{}
	query.One(&p1)
	str, err := json.Marshal(p1)
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":  "success",
		"data": string(str),
	})

	return nil
}
func UpdateProductHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("UpdateProductHandler", id)

	p := &insertproduct{}
	if err := c.Bind(p); err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "products"
	err := model.DB().Update(bson.M{"_id": bson.ObjectIdHex(id)}, p)
	if err != nil {
		log.Error("更新出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}

	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}

func GetProductInfoHandler(c echo.Context) error {
	log.Info("GetProductInfoHandler")
	id := c.QueryParam("id")
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "products"
	query, err := model.DB().QueryOne(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	p := product{}
	query.One(&p)
	str, err := json.Marshal(p)
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":  "success",
		"data": string(str),
	})

	return nil
}

func DelProductHandler(c echo.Context) error {
	id := c.QueryParam("id")
	log.Info("DelProductHandler", id)
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "products"
	err := model.DB().Remove(bson.M{"_id": bson.ObjectIdHex(id)})
	if err != nil {
		log.Error("products表删除出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Document = "production_group"
	err = model.DB().Remove(bson.M{"productid": id})
	if err != nil {
		log.Error("production_group表删除出错", err)
		// c.JSON(404, map[string]interface{}{
		// 	"msg":  "error",
		// })
		// return err
	}
	model.DB().Document = "design_group"
	err = model.DB().Remove(bson.M{"productid": id})
	if err != nil {
		log.Error("design_group表删除出错", err)
		// c.JSON(404, map[string]interface{}{
		// 	"msg":  "error",
		// })
		// return err
	}
	model.DB().Document = "editor_group"
	err = model.DB().Remove(bson.M{"productid": id})
	if err != nil {
		log.Error("editor_group表删除出错", err)
		// c.JSON(404, map[string]interface{}{
		// 	"msg":  "error",
		// })
		// return err
	}
	model.DB().Document = "face_group"
	err = model.DB().Remove(bson.M{"productid": id})
	if err != nil {
		log.Error("face_group表删除出错", err)
		// c.JSON(404, map[string]interface{}{
		// 	"msg":  "error",
		// })
		// return err
	}
	model.DB().Document = "operation_group"
	err = model.DB().Remove(bson.M{"productid": id})
	if err != nil {
		log.Error("operation_group表删除出错", err)
		// c.JSON(404, map[string]interface{}{
		// 	"msg":  "error",
		// })
		// return err
	}
	model.DB().Document = "photography_group"
	err = model.DB().Remove(bson.M{"productid": id})
	if err != nil {
		log.Error("photography_group表删除出错", err)
		// c.JSON(404, map[string]interface{}{
		// 	"msg":  "error",
		// })
		// return err
	}
	model.DB().Document = "products_issues"
	_, err = model.DB().RemoveAll(bson.M{"productid": id})
	if err != nil {
		log.Error("products_issues表删除出错", err)
		// c.JSON(404, map[string]interface{}{
		// 	"msg":  "error",
		// })
		// return err
	}
	model.DB().Document = "sku"
	_, err = model.DB().RemoveAll(bson.M{"productid": id})
	if err != nil {
		log.Error("sku表删除出错", err)
		// c.JSON(404, map[string]interface{}{
		// 	"msg":  "error",
		// })
		// return err
	}

	c.JSON(200, map[string]interface{}{
		"msg": "success",
	})

	return nil
}
